<template>
    <div class="device-search-container">
        <!-- 公共网卡和IP选择 -->
        <div class="global-network-selection">
            <a-form layout="inline" style="margin-bottom: 24px;">
                <a-form-item>
                    <a-checkbox v-model="globalSettings.useNic">网卡</a-checkbox>
                </a-form-item>
                <a-form-item>
                    <a-select
                        v-model="globalSettings.selectedNic"
                        :disabled="!globalSettings.useNic"
                        style="width: 300px;"
                        placeholder="请选择网卡"
                        @change="handleGlobalNicChange"
                    >
                        <a-select-option 
                            v-for="adapter in networkAdapters" 
                            :key="adapter.id"
                            :value="adapter.id"
                        >
                            {{ adapter.description }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="IP">
                    <a-select v-model="globalSettings.ip" style="width: 200px;">
                        <a-select-option 
                            v-for="ip in globalSettings.availableIps" 
                            :key="ip"
                            :value="ip"
                        >
                            {{ ip }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
            </a-form>
        </div>

        <a-tabs v-model="currentTab" default-active-key="auto">
            <a-tab-pane key="direct" tab="直接连接">
                <div class="connect-form-wrapper">
                    <div class="bottom-actions">
                        <a-form layout="inline">
                            <a-form-item label="端口">
                                <a-input v-model="directConnect.port" style="width: 100px;" />
                            </a-form-item>
                            <a-form-item>
                                <a-button type="primary" @click="handleDirectConnect">开始连接</a-button>
                            </a-form-item>
                        </a-form>
                    </div>
                </div>
            </a-tab-pane>
            <a-tab-pane key="hub" tab="hub连接">
                <div class="connect-form-wrapper">
                    <div class="connect-form">
                        <a-form layout="inline">
                            <a-form-item label="使用此IP">
                                <a-input
                                    v-model="hubConnect.customIp"
                                    placeholder="请输入IP地址"
                                    style="width: 240px;"
                                />
                            </a-form-item>
                        </a-form>
                    </div>
                    <div class="bottom-actions">
                        <a-form layout="inline">
                            <a-form-item label="端口">
                                <a-input v-model="hubConnect.port" style="width: 100px;" />
                            </a-form-item>
                            <a-form-item>
                                <a-button type="primary" @click="handleHubConnect">开始连接</a-button>
                            </a-form-item>
                        </a-form>
                    </div>
                </div>
            </a-tab-pane>
            <a-tab-pane key="auto" tab="自动搜索">
                <div class="auto-search-container">
                    <!-- 设备列表 -->
                    <div class="devices-list">
                        <div class="table-header">
                            <span class="table-title">设备列表</span>
                            <a-button 
                                size="small" 
                                icon="reload" 
                                :loading="loading"
                                @click="refreshDevices"
                            >
                                刷新
                            </a-button>
                        </div>
                        <a-table
                            :columns="columns"
                            :data-source="devices"
                            :loading="loading"
                            :pagination="pagination"
                            :locale="{ emptyText: loading ? '正在加载设备列表...' : '暂无设备数据，请点击刷新重试' }"
                            row-key="id"
                            size="middle"
                        >
                            <template slot="actions" slot-scope="text, record">
                                <a-button size="small" @click="connectToDevice(record)">连接</a-button>
                            </template>
                        </a-table>
                    </div>

                    <!-- 连接控件 -->
                    <div class="connection-controls">
                        <a-form layout="inline" style="margin-top: 16px;">
                            <a-form-item label="端口">
                                <a-input v-model="autoSearch.port" style="width: 100px;" />
                            </a-form-item>
                            <a-form-item>
                                <a-button type="primary" @click="handleAutoConnect">开始连接</a-button>
                            </a-form-item>
                        </a-form>
                    </div>
                </div>
            </a-tab-pane>
        </a-tabs>
    </div>
</template>

<script>
import DeviceTabManager from '@/api/TabManager/DeviceTabManager'
import { mapGetters } from 'vuex'

export default {
    name: 'DeviceSearch',
    data() {
        return {
            deviceTabManager: new DeviceTabManager(),
            networkAdapters: [], // 网卡列表
            // 全局网卡和IP设置
            globalSettings: {
                useNic: true,
                selectedNic: null,
                ip: '0.0.0.0',
                availableIps: ['0.0.0.0']
            },
            directConnect: {
                port: '8888'
            },
            hubConnect: {
                port: '8888',
                customIp: ''
            },
            autoSearch: {
                port: '8888'
            },
            loading: false,
            devices: [],
            currentTab: 'direct', // 添加currentTab属性，默认为'direct'
            pagination: {
                current: 1,
                pageSize: 10,
                total: 0,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
            },
            columns: [
                {
                    title: 'IP地址',
                    dataIndex: 'ip',
                    key: 'ip',
                    width: '30%'
                },
                {
                    title: 'MAC地址',
                    dataIndex: 'mac',
                    key: 'mac',
                    width: '40%'
                },
                {
                    title: '设备名称',
                    dataIndex: 'name',
                    key: 'name',
                    width: '20%'
                },
                {
                    title: '操作',
                    key: 'actions',
                    width: '10%',
                    scopedSlots: { customRender: 'actions' }
                }
            ]
        }
    },
    computed: {
        ...mapGetters('groupTree', ['selectedDeviceInfo', 'deviceConnection']),
        
        currentGateWayType() {
            return this.selectedDeviceInfo.gatewayType // 返回网关类型
        }
    },
    mounted() {
        this.loadNetworkAdapters()
        // this.initDeviceList()
    },
    methods: {
        // 加载网卡列表
        async loadNetworkAdapters() {
            try {
                console.log('🔍 [DeviceSearch] 加载网卡列表')
                const response = await this.deviceTabManager.getNetworkAdapters()
                
                if (response.code !== 0) {
                    console.error('❌ [DeviceSearch] 获取网卡列表失败:', response.message)
                    return
                }
                
                // 解析网卡数据
                let adapters = []
                if (response.data) {
                    if (typeof response.data === 'string') {
                        adapters = JSON.parse(response.data)
                    } else if (Array.isArray(response.data)) {
                        adapters = response.data
                    }
                }
                
                // 处理网卡数据，为每个网卡创建一个合适的数据结构
                this.networkAdapters = adapters.map((adapter, index) => {
                    const ipAddresses = adapter.IpAddresses || []
                    const primaryIp = ipAddresses.length > 0 ? ipAddresses[0] : '0.0.0.0'
                    
                    return {
                        id: adapter.Id || `adapter_${index}`,
                        description: adapter.Description || `网卡 ${index + 1}`,
                        adapterType: adapter.AdapterType || 'Unknown',
                        ipAddresses: ipAddresses,
                        primaryIp: primaryIp,
                        macAddress: adapter.MacAddress || '',
                        gatewayAddresses: adapter.GatewayAddresses || []
                    }
                })
                
                console.log('✅ [DeviceSearch] 网卡列表加载成功:', this.networkAdapters)
                
                // 如果有网卡，默认选择第一个
                if (this.networkAdapters.length > 0) {
                    this.globalSettings.selectedNic = this.networkAdapters[0].id
                    this.globalSettings.availableIps = this.networkAdapters[0].ipAddresses.length > 0 
                        ? this.networkAdapters[0].ipAddresses 
                        : ['0.0.0.0']
                    this.globalSettings.ip = this.globalSettings.availableIps[0]
                }
                
            } catch (error) {
                console.error('❌ [DeviceSearch] 加载网卡列表失败:', error)
                this.$message.error('加载网卡列表失败: ' + (error.message || '未知错误'))
            }
        },
        
        // 处理网卡切换 (全局设置)
        handleGlobalNicChange(selectedNicId) {
            console.log('🔄 [DeviceSearch] 全局网卡切换:', selectedNicId)
            
            const selectedAdapter = this.networkAdapters.find(adapter => adapter.id === selectedNicId)
            if (!selectedAdapter) {
                console.warn('⚠️ [DeviceSearch] 未找到选中的网卡')
                return
            }
            
            // 更新全局可用IP列表
            this.globalSettings.availableIps = selectedAdapter.ipAddresses.length > 0 
                ? selectedAdapter.ipAddresses 
                : ['0.0.0.0']
            this.globalSettings.ip = this.globalSettings.availableIps[0]
            console.log('✅ [DeviceSearch] 全局IP已更新:', this.globalSettings.ip)
            // 切换网卡，如果tab是direct时，需要检查selectedAdapter有没有ip地址为10.11.12.x的，如果没有，需要提示(提示需要延时5秒)
            if (this.currentTab === 'direct') {
                const is101112 = selectedAdapter.ipAddresses.some(ip => ip.startsWith('10.11.12.'))
                if (!is101112) {
                    // 提示需要保持5秒
                    this.$message.warning('当前网卡没有10.11.12.x的IP地址，请选择其他网卡', 3)
                    return
                }
            }
        },

        refreshDevices() {
            console.log('🔄 [DeviceSearch] 刷新设备列表')
            this.initDeviceList()
        },
        
        // 初始化设备列表
        async initDeviceList() {
            if (this.loading) {
                console.log('⏳ [DeviceSearch] 设备列表正在加载中，跳过重复请求')
                return
            }
            
            this.loading = true
            console.log('🔍 [DeviceSearch] 开始加载设备列表...')
            const gateWayType = this.currentGateWayType
            console.log('🔍 [DeviceSearch] 网关类型:', gateWayType)
            try {
                const BroadcastData = {
                    BroadcastMessage: gateWayType,
                    BroadcastPort: this.autoSearch.port,
                    ListenPort: 0
                }                
                const response = await this.deviceTabManager.getGateWayDeviceList(JSON.stringify(BroadcastData))
                
                if (response.code !== 0) {
                    console.warn('⚠️ [DeviceSearch] 获取设备列表失败:', response.message)
                    this.$message.warning('获取设备列表失败: ' + (response.message || '请检查网络连接'))
                    this.devices = []
                    this.pagination.total = 0
                    return
                }
                
                // 解析设备数据
                let devices = []
                if (response.data) {
                    if (typeof response.data === 'string') {
                        try {
                            devices = JSON.parse(response.data)
                        } catch (parseError) {
                            console.error('❌ [DeviceSearch] 解析设备数据失败:', parseError)
                            devices = []
                        }
                    } else if (Array.isArray(response.data)) {
                        devices = response.data
                    } else {
                        devices = []
                    }
                }
                
                // 处理设备数据
                this.devices = Array.isArray(devices)
                    ? devices.map((device, index) => ({
                        id: device.id || `device_${index}`,
                        ip: device.ip || device.IpAddress || '未知',
                        mac: device.mac || device.MacAddress || '未知',
                        name: device.name || device.Name || `设备${index + 1}`,
                        status: device.status || '未知',
                        ...device
                    }))
                    : []
                
                this.pagination.total = this.devices.length
                
                console.log(`✅ [DeviceSearch] 设备列表加载完成，共找到 ${this.devices.length} 个设备`)
                
                if (this.devices.length === 0) {
                    this.$message.info('未发现任何设备，请检查网络连接或稍后重试')
                } else {
                    this.$message.success(`成功加载 ${this.devices.length} 个设备`)
                }
                
            } catch (error) {
                console.error('❌ [DeviceSearch] 加载设备列表异常:', error)
                this.$message.error('加载设备列表异常: ' + (error.message || '网络错误，请稍后重试'))
                this.devices = []
                this.pagination.total = 0
            } finally {
                this.loading = false
            }
        },
        
        // 处理直接连接
        async handleDirectConnect() {
            const connectData = {
                type: 'direct',
                useNic: this.globalSettings.useNic,
                selectedNic: this.globalSettings.selectedNic,
                ip: this.globalSettings.ip,
                port: this.directConnect.port
            }
            
            console.log('🔌 [DeviceSearch] 开始直接连接:', connectData)
            
            try {
                const response = await this.deviceTabManager.directConnect(JSON.stringify(connectData))
                
                if (response.code === 0) {
                    this.$message.success(`直接连接成功: ${connectData.ip}:${connectData.port}`)
                    // 连接成功后，向父组件传递IP和端口信息
                    this.$emit('connection-success', {
                        ip: connectData.ip,
                        port: connectData.port,
                        type: 'direct'
                    })
                } else {
                    this.$message.error(`直接连接失败: ${response.msg || '未知错误'}`)
                }
            } catch (error) {
                console.error('❌ [DeviceSearch] 直接连接失败:', error)
                this.$message.error('直接连接失败: ' + (error.msg || '未知错误'))
            }
        },
        
        // 处理Hub连接
        async handleHubConnect() {
            const connectData = {
                type: 'hub',
                useNic: this.globalSettings.useNic,
                selectedNic: this.globalSettings.selectedNic,
                ip: this.hubConnect.customIp || this.globalSettings.ip,
                port: this.hubConnect.port
            }
            
            console.log('🔌 [DeviceSearch] 开始Hub连接:', connectData)
            
            try {
                const response = await this.deviceTabManager.hubConnect(JSON.stringify(connectData))
                
                if (response.code === 0) {
                    this.$message.success(`Hub连接成功: ${connectData.ip}:${connectData.port}`)
                    // 连接成功后，向父组件传递IP和端口信息
                    this.$emit('connection-success', {
                        ip: connectData.ip,
                        port: connectData.port,
                        type: 'hub'
                    })
                } else {
                    this.$message.error(`Hub连接失败: ${response.msg || '未知错误'}`)
                }
            } catch (error) {
                console.error('❌ [DeviceSearch] Hub连接失败:', error)
                this.$message.error('Hub连接失败: ' + (error.msg || '未知错误'))
            }
        },

        // 处理自动连接
        async handleAutoConnect() {
            const connectData = {
                type: 'auto',
                useNic: this.globalSettings.useNic,
                selectedNic: this.globalSettings.selectedNic,
                ip: this.globalSettings.ip,
                port: this.autoSearch.port
            }

            console.log('🔌 [DeviceSearch] 开始自动连接:', connectData)
            
            try {
                const response = await this.deviceTabManager.autoConnect(JSON.stringify(connectData))
                
                if (response.code === 0) {
                    this.$message.success(`自动连接成功: ${connectData.ip}:${connectData.port}`)
                    // 连接成功后，向父组件传递IP和端口信息
                    this.$emit('connection-success', {
                        ip: connectData.ip,
                        port: connectData.port,
                        type: 'auto'
                    })
                } else {
                    this.$message.error(`自动连接失败: ${response.msg || '未知错误'}`)
                }
            } catch (error) {
                console.error('❌ [DeviceSearch] 自动连接失败:', error)
                this.$message.error('自动连接失败: ' + (error.msg || '未知错误'))
            }
        },

        // 连接到设备 (用于自动搜索的连接按钮)
        async connectToDevice(device) {
            const connectData = {
                type: 'auto',
                useNic: this.globalSettings.useNic,
                selectedNic: this.globalSettings.selectedNic,
                ip: device.ip, // 使用设备列表中的IP
                port: this.autoSearch.port,
                deviceInfo: device // 添加设备信息
            }

            console.log('🔌 [DeviceSearch] 连接到设备:', connectData)
            
            try {
                const response = await this.deviceTabManager.connectDevice(connectData)
                
                if (response.code === 0) {
                    this.$message.success(`连接到设备成功: ${connectData.ip}:${connectData.port}`)
                    // 连接成功后，向父组件传递IP和端口信息
                    this.$emit('connection-success', {
                        ip: connectData.ip,
                        port: connectData.port,
                        type: 'device',
                        deviceInfo: device
                    })
                } else {
                    this.$message.error(`连接到设备失败: ${response.message || '未知错误'}`)
                }
            } catch (error) {
                console.error('❌ [DeviceSearch] 连接到设备失败:', error)
                this.$message.error('连接到设备失败: ' + (error.message || '未知错误'))
            }
        }
    }
}
</script>

<style scoped>
.device-search-container {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.global-network-selection {
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 24px;
    border: 1px solid #e8e8e8;
}
.connect-form-wrapper {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    min-height: 150px;
}
.connect-form {
    padding-top: 24px;
}
.bottom-actions {
    align-self: flex-start;
    margin-top: 24px;
}
.auto-search-container {
    display: flex;
    flex-direction: column;
    gap: 24px;
}
.connection-controls {
    align-self: flex-start;
    margin-top: 24px;
}
.devices-list {
    margin-top: 16px;
}
.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}
.table-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
}

/* 表格样式优化 */
.device-search-container >>> .ant-table-thead > tr > th {
    background-color: #fafafa;
    font-weight: 600;
}
.device-search-container >>> .ant-table-tbody > tr:hover > td {
    background-color: #f5f5f5;
}

/* 加载状态优化 */
.device-search-container >>> .ant-table-loading {
    min-height: 200px;
}
.device-search-container >>> .ant-spin-container {
    min-height: 200px;
}

/* 空状态优化 */
.device-search-container >>> .ant-empty {
    padding: 40px 0;
}
</style> 